/*
 * Copyright 2007-2010 Jeremy Brown.
 *
 * Licensed under the Apache License, Version 2.0 (the "License")
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @author <a href="http://jeremy-brown.com">Jeremy Brown</a>
 */


package groovy.prefuse.factory

import prefuse.action.*
import prefuse.action.distortion.*
import prefuse.Visualization

public class DistortionFactory extends ActionFactory
{
	private Class klass
	
	public DistortionFactory(){}
	
	public DistortionFactory(Class klass)
	{
		this.klass = klass
	}
	
	boolean isLeaf()
	{
		return true
	}
    
    public Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes) throws InstantiationException, IllegalAccessException
	{
		builder.context.put("name", attributes.remove("name")) //Action will be added to Visualization with this name
		
		if(value == null && attributes.distortion)
		{
			value = attributes.remove("distortion")
		}
		
		if(value instanceof Distortion)
		{
			return value
		}
		
		if(klass)
		{
			buildClass = klass
		}
		else if(value instanceof Class)
		{
			buildClass = value
			value = null
		}

		def action = null
		
		if(buildClass instanceof Class && Distortion.isAssignableFrom(buildClass))
		{
			//constructor with no parameters
			if(FisheyeDistortion.equals(buildClass))
			{
				action = new FisheyeDistortion()
			}
			
			else if(BifocalDistortion.equals(buildClass))
			{
				if(attributes.range && attributes.magnification)
				{
					action = new BifocalDistortion(attributes.remove("range"), attributes.remove("magnification"))
				}
				else
				{
					action = new BifocalDistortion()
				}
			}
			
			//Try to instantiate the Action with a no-parameter-constructor
			else
			{
				action = buildClass.newInstance()
			}
		}

		return action
	}
}
